<template>
  <div class="devices-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>设备管理</span>
          <el-button type="primary" @click="openAddDialog">
            <el-icon><Plus /></el-icon>
            添加设备
          </el-button>
        </div>
      </template>

      <el-table :data="devices" v-loading="loading" stripe>
        <el-table-column prop="name" label="设备名称" width="150" />
        <el-table-column prop="ip_address" label="IP地址" width="150" />
        <el-table-column label="设备类型" width="120">
          <template #default="{ row }">
            {{ formatDeviceType(row.device_type) }}
          </template>
        </el-table-column>
        <el-table-column prop="hostname" label="主机名" width="150" />
        <el-table-column label="自动备份" width="100">
          <template #default="{ row }">
            <el-switch v-model="row.auto_backup" @change="updateDevice(row)" />
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'info'" size="small">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="420">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="testConnection(row)">测试</el-button>
            <el-button type="info" size="small" @click="debugDevice(row)">调试</el-button>
            <el-button type="success" size="small" @click="backupDevice(row)">备份</el-button>
            <el-button type="warning" size="small" @click="editDevice(row)">编辑</el-button>
            <el-button type="default" size="small" @click="showLogs">日志</el-button>
            <el-popconfirm title="确定删除这个设备吗？" @confirm="deleteDevice(row)">
              <template #reference>
                <el-button type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑设备对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑设备' : '添加设备'"
      width="600px"
    >
      <el-form :model="deviceForm" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="deviceForm.name" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="IP地址" prop="ip_address">
          <el-input v-model="deviceForm.ip_address" placeholder="请输入IP地址" />
        </el-form-item>
        <el-form-item label="主机名" prop="hostname">
          <el-input v-model="deviceForm.hostname" placeholder="请输入主机名" />
        </el-form-item>
        <el-form-item label="设备类型" prop="device_type">
          <el-select v-model="deviceForm.device_type" placeholder="请选择设备类型" style="width: 100%;">
            <el-option
              v-for="type in deviceTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            >
              <div>
                <div>{{ type.label }}</div>
                <div style="font-size: 12px; color: #999;">{{ type.description }}</div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="端口" prop="port">
          <el-input-number v-model="deviceForm.port" :min="1" :max="65535" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="deviceForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="deviceForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="Enable密码">
          <el-input v-model="deviceForm.enable_password" type="password" placeholder="可选" show-password />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="deviceForm.description" type="textarea" :rows="3" placeholder="设备描述" />
        </el-form-item>
        <el-form-item label="自动备份">
          <el-switch v-model="deviceForm.auto_backup" />
        </el-form-item>
        <el-form-item label="备份间隔(小时)" prop="backup_interval">
          <el-input-number v-model="deviceForm.backup_interval" :min="1" :max="168" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 实时日志对话框 -->
    <el-dialog
      v-model="logDialogVisible"
      title="实时日志"
      width="90%"
      :before-close="handleLogDialogClose"
    >
      <div class="log-container">
        <div class="log-header">
          <el-button @click="clearLogs" size="small">清空日志</el-button>
          <el-button @click="toggleAutoScroll" size="small" :type="autoScroll ? 'primary' : ''">
            {{ autoScroll ? '停止自动滚动' : '自动滚动' }}
          </el-button>
        </div>
        <div ref="logContainer" class="log-content">
          <div 
            v-for="(log, index) in logs" 
            :key="index" 
            :class="['log-item', `log-${log.level.toLowerCase()}`]"
          >
            <span class="log-time">{{ log.time }}</span>
            <span class="log-level">[{{ log.level }}]</span>
            <span class="log-message">{{ log.message }}</span>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 调试对话框 -->
    <el-dialog
      v-model="debugDialogVisible"
      title="设备命令调试"
      width="80%"
      :before-close="handleDebugDialogClose"
    >
      <div v-if="debugResult">
        <el-descriptions :column="2" border style="margin-bottom: 20px;">
          <el-descriptions-item label="设备名称">{{ debugResult.device?.name || '未知' }}</el-descriptions-item>
          <el-descriptions-item label="IP地址">{{ debugResult.device?.ip_address || '未知' }}</el-descriptions-item>
          <el-descriptions-item label="设备类型">{{ debugResult.device?.device_type || '未知' }}</el-descriptions-item>
          <el-descriptions-item label="设备提示符">{{ debugResult.device?.prompt || '未知' }}</el-descriptions-item>
        </el-descriptions>

        <el-alert 
          :title="`测试了 ${debugResult.commands_tested || 0} 个命令，成功 ${debugResult.summary?.successful_commands || 0} 个，失败 ${debugResult.summary?.failed_commands || 0} 个`"
          :type="(debugResult.summary?.successful_commands || 0) > 0 ? 'success' : 'error'"
          style="margin-bottom: 20px;"
        />

        <el-table :data="debugResult.results || []" stripe>
          <el-table-column prop="command" label="命令" width="200" />
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.success && !row.has_errors ? 'success' : 'danger'" size="small">
                {{ row.success && !row.has_errors ? '成功' : '失败' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="result_length" label="结果长度" width="100" />
          <el-table-column label="结果预览" show-overflow-tooltip>
            <template #default="{ row }">
              <div v-if="row.result_preview" style="font-family: monospace; font-size: 12px;">
                {{ row.result_preview }}
              </div>
              <div v-else-if="row.error" style="color: red;">
                {{ row.error }}
              </div>
              <div v-else style="color: gray;">
                无结果
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div v-if="debugResult.summary.best_command" style="margin-top: 20px;">
          <el-alert 
            :title="`推荐命令: ${debugResult.summary.best_command.command} (长度: ${debugResult.summary.best_command.result_length} 字符)`"
            type="success"
            :closable="false"
          />
        </div>
      </div>
      <div v-else-if="debugLoading">
        <el-skeleton :rows="5" animated />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { deviceApi } from '@/api'
import { ElMessage, ElLoading } from 'element-plus'

const loading = ref(false)
const devices = ref([])
const deviceTypes = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)
const debugDialogVisible = ref(false)
const debugResult = ref(null)
const debugLoading = ref(false)
const logDialogVisible = ref(false)
const logs = ref([])
const autoScroll = ref(true)
const logContainer = ref(null)
const deviceForm = ref({
  name: '',
  ip_address: '',
  hostname: '',
  device_type: 'cisco_ios',
  port: 22,
  username: '',
  password: '',
  enable_password: '',
  description: '',
  auto_backup: true,
  backup_interval: 24,
  is_active: true
})

const rules = {
  name: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
  ip_address: [{ required: true, message: '请输入IP地址', trigger: 'blur' }],
  hostname: [{ required: true, message: '请输入主机名', trigger: 'blur' }],
  device_type: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (Array.isArray(value)) {
          callback(new Error('密码格式错误'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

const loadDevices = async () => {
  loading.value = true
  try {
    devices.value = await deviceApi.getDevices()
  } catch (error) {
    ElMessage.error('加载设备列表失败')
  } finally {
    loading.value = false
  }
}

const loadDeviceTypes = async () => {
  try {
    const result = await deviceApi.getDeviceTypes()
    deviceTypes.value = result.device_types
  } catch (error) {
    ElMessage.error('加载设备类型失败')
  }
}

const formatDeviceType = (deviceType) => {
  const type = deviceTypes.value.find(t => t.value === deviceType)
  return type ? type.label : deviceType
}

const resetForm = () => {
  deviceForm.value = {
    name: '',
    ip_address: '',
    hostname: '',
    device_type: 'cisco_ios',
    port: 22,
    username: '',
    password: '',
    enable_password: '',
    description: '',
    auto_backup: true,
    backup_interval: 24,
    is_active: true
  }
  // 清除表单验证状态
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const openAddDialog = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const formatTime = (time) => {
  return new Date(time).toLocaleString('zh-CN')
}


const editDevice = (row) => {
  isEdit.value = true
  // 确保密码字段是字符串
  deviceForm.value = {
    ...row,
    password: typeof row.password === 'string' ? row.password : '',
    enable_password: typeof row.enable_password === 'string' ? row.enable_password : ''
  }
  dialogVisible.value = true
}

const submitForm = async () => {
  try {
    // 验证表单
    await formRef.value.validate()
    
    // 准备提交的数据
    const formData = { ...deviceForm.value }
    
    // 确保密码字段是字符串
    if (Array.isArray(formData.password)) {
      formData.password = formData.password[0] || ''
    }
    if (Array.isArray(formData.enable_password)) {
      formData.enable_password = formData.enable_password[0] || ''
    }
    
    if (isEdit.value) {
      await deviceApi.updateDevice(formData.id, formData)
      ElMessage.success('设备更新成功')
    } else {
      await deviceApi.createDevice(formData)
      ElMessage.success('设备添加成功')
    }
    dialogVisible.value = false
    loadDevices()
  } catch (error) {
    console.error('表单提交错误:', error)
    if (error && typeof error === 'object' && 'password' in error) {
      ElMessage.error('表单验证失败，请检查输入内容')
    } else {
      ElMessage.error(error.response?.data?.detail || '操作失败')
    }
  }
}

const updateDevice = async (row) => {
  try {
    await deviceApi.updateDevice(row.id, { auto_backup: row.auto_backup })
    ElMessage.success('设置已更新')
  } catch (error) {
    ElMessage.error('更新失败')
    loadDevices()
  }
}

const deleteDevice = async (row) => {
  try {
    await deviceApi.deleteDevice(row.id)
    ElMessage.success('设备已删除')
    loadDevices()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

const testConnection = async (row) => {
  addLog(`开始测试设备连接: ${row.name} (${row.ip_address})`, 'INFO')
  
  const loading = ElLoading.service({
    lock: true,
    text: '正在测试连接...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  try {
    const result = await deviceApi.testConnection(row.id)
    loading.close()
    if (result.success) {
      addLog(`设备连接测试成功: ${row.name}`, 'SUCCESS')
      ElMessage.success(result.message)
    } else {
      addLog(`设备连接测试失败: ${row.name} - ${result.message}`, 'ERROR')
      ElMessage.error(result.message)
    }
  } catch (error) {
    loading.close()
    addLog(`设备连接测试异常: ${row.name} - ${error.message}`, 'ERROR')
    ElMessage.error('测试失败')
  }
}

const backupDevice = async (row) => {
  addLog(`开始备份设备: ${row.name} (${row.ip_address})`, 'INFO')
  
  const loading = ElLoading.service({
    lock: true,
    text: '正在备份...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  try {
    await deviceApi.triggerBackup(row.id)
    loading.close()
    addLog(`设备备份成功: ${row.name}`, 'SUCCESS')
    ElMessage.success('备份成功')
  } catch (error) {
    loading.close()
    const errorMsg = error.response?.data?.detail || '备份失败'
    addLog(`设备备份失败: ${row.name} - ${errorMsg}`, 'ERROR')
    ElMessage.error(errorMsg)
  }
}

const debugDevice = async (row) => {
  debugDialogVisible.value = true
  debugLoading.value = true
  debugResult.value = null
  
  try {
    const result = await deviceApi.debugDevice(row.id)
    debugResult.value = result
    if (result.error) {
      ElMessage.error(result.error)
    } else {
      ElMessage.success('调试完成')
    }
  } catch (error) {
    ElMessage.error('调试失败: ' + (error.response?.data?.detail || error.message))
  } finally {
    debugLoading.value = false
  }
}

const handleDebugDialogClose = () => {
  debugDialogVisible.value = false
  debugResult.value = null
  debugLoading.value = false
}

const addLog = (message, level = 'INFO') => {
  const now = new Date()
  const time = now.toLocaleTimeString()
  logs.value.push({
    time,
    level,
    message
  })
  
  // 限制日志数量
  if (logs.value.length > 1000) {
    logs.value = logs.value.slice(-500)
  }
  
  // 自动滚动到底部
  if (autoScroll.value) {
    nextTick(() => {
      if (logContainer.value) {
        logContainer.value.scrollTop = logContainer.value.scrollHeight
      }
    })
  }
}

const clearLogs = () => {
  logs.value = []
}

const toggleAutoScroll = () => {
  autoScroll.value = !autoScroll.value
}

const handleLogDialogClose = () => {
  logDialogVisible.value = false
}

const showLogs = () => {
  logDialogVisible.value = true
}

onMounted(() => {
  loadDevices()
  loadDeviceTypes()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
}

/* 日志样式 */
.log-container {
  height: 600px;
  display: flex;
  flex-direction: column;
}

.log-header {
  padding: 10px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  gap: 10px;
}

.log-content {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  background-color: #1e1e1e;
  color: #ffffff;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.4;
}

.log-item {
  margin-bottom: 2px;
  padding: 2px 0;
  border-bottom: 1px solid #333;
}

.log-time {
  color: #888;
  margin-right: 10px;
}

.log-level {
  margin-right: 10px;
  font-weight: bold;
}

.log-info .log-level {
  color: #4fc3f7;
}

.log-success .log-level {
  color: #4caf50;
}

.log-error .log-level {
  color: #f44336;
}

.log-warning .log-level {
  color: #ff9800;
}

.log-debug .log-level {
  color: #9c27b0;
}

.log-message {
  color: #ffffff;
}
</style>

